exports.plugin = {
  name: "classesModel",
  register: (server) => {
    const { mongoose } = server;
    const schema = mongoose.Schema({
      classname: String,
      ctime: {
        type: Date,
        default: Date.now,
      },
    });

    schema.methods = {
      // 获取班级总数
      getClassesCount({ searchField, searchValue }) {
        const conditions = {};
        if (searchField && searchValue) {
          conditions[searchField] = {
            $regex: new RegExp(`.*${searchValue}.*`, "i"),
          };
        }
        return this.model("classes").find(conditions).countDocuments();
      },
      // 获取班级
      getClasses(
        { page, perPage, searchField, searchValue } = {
          page: 1,
          perPage: 10,
        }
      ) {
        const conditions = {};
        if (searchField && searchValue) {
          conditions[searchField] = {
            $regex: new RegExp(`.*${searchValue}.*`, "i"),
          };
        }
        return this.model("classes")
          .find(conditions, { __v: 0 })
          .skip((page - 1) * perPage)
          .limit(perPage)
          .sort({ ctime: -1 });
      },
      // 添加班级
      addClasses(data) {
        return this.model("classes").create(data);
      },
      // 根据ID获取单个班级信息
      getClassById(_id) {
        return this.model("classes").findById(_id, { __v: 0 });
      },
      // 根据ID删除班级
      deleteClassById(_id) {
        return this.model("classes").deleteOne({ _id });
      },
      // 根据多个ID批量删除班级
      deleteClassesByIds(ids) {
        return this.model("classes").deleteMany({ _id: { $in: ids } });
      },
      // 根据ID更新班级信息
      updateClassById(_id, data) {
        return this.model("classes").updateOne({ _id }, data);
      },
      // 判断字段值是否存在
      isExist(field, value) {
        return this.model("classes").findOne({ [field]: value });
      },
    };
    const Classes = mongoose.model("classes", schema);
    server.decorate("request", "classesModel", new Classes());
  },
};
